package SaveServlet.course;

import com.lyq.bean.Course;
import com.lyq.bean.CourseSchedule;
import com.lyq.bean.service.E_Service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/Schedule_Servlet")
public class Schedule_Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public Schedule_Servlet() {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String campus = request.getParameter("campus");
        String semester = request.getParameter("semester");
        
        if (id == null) {
            id = "seekall"; // 默认显示当前学生已选课程
        }
        
        if (campus == null) {
            campus = "";
        }

        if (semester == null || semester.isEmpty()) {
            semester = "2025-2026秋季学期"; // 默认学期
        }
        
        if (id.equals("seekall")) {
            // 获取当前登录学生的学号
            String studentNo = (String) request.getSession().getAttribute("UNAME");

            // 获取学生已选课程
            List<Course> studentCourses = new ArrayList<>();
            studentCourses = (new E_Service()).seek_ElectC(studentNo);
            
            // 根据校区和学期筛选课程
            studentCourses = this.filterByCampusAndSemester(studentCourses, campus, semester);
            
            // 转换为CourseSchedule对象列表
            List<CourseSchedule> courseSchedules = convertToCourseSchedules(studentCourses);
            
            request.setAttribute("courseSchedules", courseSchedules);
            request.setAttribute("semester", semester);
            request.setAttribute("campus", campus);
            request.setAttribute("list", studentCourses);
        }
        
        // 转发到课表页面
        request.getRequestDispatcher("/jsp/course/s/MySchedule.jsp").forward(request, response);
    }
    
    // 根据校区和学期筛选课程
    private List<Course> filterByCampusAndSemester(List<Course> courses, String campus, String semester) {
        List<Course> filteredCourses = new ArrayList<>();
        for (Course course : courses) {
            boolean campusMatch = true;
            boolean semesterMatch = true;
            
            // 校区筛选
            if (campus != null && !campus.isEmpty()) {
                campusMatch = (course.getCampus() != null && course.getCampus().equals(campus));
            }
            
            // 学期筛选
            if (semester != null && !semester.isEmpty()) {
                semesterMatch = (course.getSemester() != null && course.getSemester().equals(semester));
            }
            
            // 只有当校区和学期都匹配时才添加到结果中
            if (campusMatch && semesterMatch) {
                filteredCourses.add(course);
            }
        }
        return filteredCourses;
    }
    
    // 将Course列表转换为CourseSchedule列表
    private List<CourseSchedule> convertToCourseSchedules(List<Course> courses) {
        List<CourseSchedule> courseSchedules = new ArrayList<>();
        
        for (Course course : courses) {
            // 解析课程时间
            List<CourseSchedule> schedules = parseCourseTime(course);
            courseSchedules.addAll(schedules);
        }
        
        return courseSchedules;
    }
    
    // 解析课程时间
    private List<CourseSchedule> parseCourseTime(Course course) {
        List<CourseSchedule> schedules = new ArrayList<>();
        
        String courseTime = course.getTime();
        
        // 处理空或无效的时间数据
        if (courseTime == null || courseTime.isEmpty() || courseTime.equals("1")) {
            // 对于无效数据，我们创建一个默认的课程安排（放在第一周周一第一节）
            CourseSchedule schedule = new CourseSchedule();
            schedule.setCourseNo(course.getNo());
            schedule.setCourseName(course.getName());
            schedule.setTeacher(course.getTeacher());
            schedule.setPlace(course.getPlace());
            schedule.setTime(course.getTime());
            schedule.setDayOfWeek(1);  // 周一
            schedule.setStartSession(1);  // 第1节
            schedule.setEndSession(1);   // 第1节
            schedules.add(schedule);
            return schedules;
        }
        
        // 分割多个时间段，例如："星期一 11-12节, 星期日 3-4节"
        String[] timeSlots = courseTime.split(",");
        
        for (String timeSlot : timeSlots) {
            timeSlot = timeSlot.trim();
            // 解析每个时间段，例如："星期一 11-12节"
            if (timeSlot.startsWith("星期")) {
                try {
                    // 提取星期几
                    int dayOfWeek = 0;
                    if (timeSlot.startsWith("星期一")) {
                        dayOfWeek = 1;
                    } else if (timeSlot.startsWith("星期二")) {
                        dayOfWeek = 2;
                    } else if (timeSlot.startsWith("星期三")) {
                        dayOfWeek = 3;
                    } else if (timeSlot.startsWith("星期四")) {
                        dayOfWeek = 4;
                    } else if (timeSlot.startsWith("星期五")) {
                        dayOfWeek = 5;
                    } else if (timeSlot.startsWith("星期六")) {
                        dayOfWeek = 6;
                    } else if (timeSlot.startsWith("星期日")) {
                        dayOfWeek = 7;
                    }
                    
                    // 提取节次范围
                    int startSession = 0;
                    int endSession = 0;
                    
                    // 查找节次信息，例如："11-12节"
                    int sectionStartIndex = timeSlot.indexOf(" ");
                    if (sectionStartIndex > 0) {
                        String sectionInfo = timeSlot.substring(sectionStartIndex + 1);
                        // 移除"节"字
                        sectionInfo = sectionInfo.replace("节", "").trim();
                        // 分割起始和结束节次
                        String[] sections = sectionInfo.split("-");
                        if (sections.length >= 2) {
                            startSession = Integer.parseInt(sections[0]);
                            endSession = Integer.parseInt(sections[1]);
                        } else if (sections.length == 1) {
                            startSession = Integer.parseInt(sections[0]);
                            endSession = startSession;
                        }
                    }
                    
                    CourseSchedule schedule = new CourseSchedule();
                    schedule.setCourseNo(course.getNo());
                    schedule.setCourseName(course.getName());
                    schedule.setTeacher(course.getTeacher());
                    schedule.setPlace(course.getPlace());
                    schedule.setTime(course.getTime());
                    schedule.setDayOfWeek(dayOfWeek);
                    schedule.setStartSession(startSession);
                    schedule.setEndSession(endSession);
                    
                    schedules.add(schedule);
                } catch (Exception e) {
                    // 解析出错时跳过该时间段
                    System.out.println("解析时间出错: " + timeSlot);
                    e.printStackTrace();
                }
            }
        }
        
        return schedules;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}